#include "upushbutton.h"

#include <QPainterPath>
#include <QStyle>
#include <QStyleOption>
#include <QStylePainter>

constexpr int margins = 10;

UPushButton::UPushButton(const QString text, QWidget* parent)
    : QPushButton(text, parent)
{
    QFont f = font();
    f.setPixelSize(16);
    setFlat(true);
    setContentsMargins(margins, margins, contentsMargins().top(), contentsMargins().bottom());
}

UPushButton::UPushButton(QWidget* parent) : QPushButton(parent)
{
    QFont f = font();
    f.setPixelSize(16);
    setFlat(true);
    setContentsMargins(margins, margins, contentsMargins().top(), contentsMargins().bottom());
}

UPushButton::~UPushButton()
{
}

void UPushButton::setButtonType(const ButtonType &type)
{
    if (m_type != type)
    {
        m_type = type;
        update();
    }
}

void UPushButton::setRadius(int radius)
{
    if (m_radius != radius)
    {
        m_radius = radius;
        update();
    }
}

void UPushButton::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event)

    QStyleOptionButton btn;
    initStyleOption(&btn);
    QStylePainter stylePainter(this);
    stylePainter.setRenderHint(QPainter::Antialiasing);
    QRectF rect = this->rect();

    qreal opacity = isEnabled() ? 1.0 : 0.4;
    stylePainter.setOpacity(opacity);
    QColor brush = (m_type == ButtonType::ButtonNormal) ? palette().color(QPalette::Button) : Qt::transparent;
    stylePainter.setBrush(brush);
    stylePainter.setPen(Qt::NoPen);
    if (btn.state & QStyle::State_Enabled)
    {
        if (btn.state & QStyle::State_MouseOver)
            stylePainter.setBrush((m_type == ButtonType::ButtonNormal) ? brush.darker(120) : palette().color(QPalette::Button));
    }

    if (isDown())
        stylePainter.setBrush((m_type == ButtonType::ButtonNormal) ? brush.darker(140) : palette().color(QPalette::Button).darker(120));

    if (isChecked())
        stylePainter.setBrush(palette().color(QPalette::Highlight));

    QPainterPath painterPath;
    painterPath.addRoundedRect(rect, m_radius, m_radius);
    stylePainter.drawPath(painterPath);

    stylePainter.drawControl(QStyle::CE_PushButtonLabel, btn);
}
